﻿namespace EFS.RC.CCAdmin.AD
{
	public partial class Search : EFS.RC.CCAdmin.Common.Control
	{
		#region Locals
		/// lock list
		private System.Object loadDataGridSync = new System.Object();
		#endregion

		public Search()
		{
			InitializeComponent();

			// ignore in desiger
			if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
			{
				UtilitiesService.SearchDomainUsersCompleted += new System.EventHandler<WebProxy.SearchDomainUsersCompletedEventArgs>(UtilitiesService_SearchDomainUsersCompleted);
				textBoxName.Focus();
			}
		}

		#region Properties
		/// Property IsValid: Get
		public System.Boolean? IsValid
		{
			get
			{
				return null != SelectedUser;
			}
		}

		/// Property SelectedUser: Get
		public EFS.AD.User SelectedUser
		{
			get
			{
				return (EFS.AD.User)dataGridResults.SelectedItem;
			}
		}

		/// Property IsValid: Get
		private System.String SearchText
		{
			get
			{
				return EFS.Common.Functions.String.GetLowerTrimmedString(textBoxName.Text);
			}
		}
		#endregion

		#region WS calls
		/// SearchDomainUsersCompleted
		private void UtilitiesService_SearchDomainUsersCompleted(object sender, WebProxy.SearchDomainUsersCompletedEventArgs e)
		{
			lock (loadDataGridSync)
			{
				try
				{
					if (null != e.Error)
					{
						throw e.Error;
					}

					// deserialize
					EFS.AD.User[] users = EFS.Common.Serialization.Functions.Deserialize<EFS.AD.User[]>(e.Result.ToString());

					//bind/fill form
					dataGridResults.ItemsSource = users;
				}
				catch (System.Exception ex)
				{
					ShowErrorMessage("Unable to load data! " + ex.Message);
				}
			}
		}
		#endregion

		#region Control Events
		/// TextBox change
		private void textBoxName_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
		{
			// only if more than 3 chars
			if (!EFS.Common.Verify.String(SearchText) || SearchText.Length < 3)
			{
				return;
			}

			// clear list
			dataGridResults.ItemsSource = null;

			// make the async call
			UtilitiesService.SearchDomainUsersAsync(SearchText);
		}
		#endregion
	}

}